package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 营业额统计报表
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDateList(begin, end);

        String dateStr = StringUtils.join(dateList, ",");

        //目标2：营业额，以逗号分隔，例如：406.0,1520.0,75.0
        List<Double> turnoverList = new ArrayList<>();
        //select sum(amount) from orders where status=？ and order_time>?  and order_time< ?
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin", beginTime);
            map.put("end", endTime);
            Double sumAmonut = ordersMapper.getAmountByStatusAndOrderTime(map);

            sumAmonut = sumAmonut == null ? 0.0 : sumAmonut;

            turnoverList.add(sumAmonut);
        }

        String turnoverStr = StringUtils.join(turnoverList, ",");

        return TurnoverReportVO.builder()
                .dateList(dateStr)
                .turnoverList(turnoverStr)
                .build();
    }

    private List<LocalDate> getLocalDateList(LocalDate begin, LocalDate end) {
        //目标1：日期，以逗号分隔，例如：2022-10-05,  ,2022-10-05
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //目标1：日期，以逗号分隔，例如：2022-10-05,  ,2022-10-05
        List<LocalDate> dateList = getLocalDateList(begin, end);

        String dateStr = StringUtils.join(dateList, ",");
        //目标2：用户总量，以逗号分隔，例如：200,210,220
        //目标3：新增用户，以逗号分隔，例如：20,21,10
        List<Integer> newUserConunts = new ArrayList<>();
        List<Integer> totalUserConunts = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //统计当天新增用户 select count(*) from user where create_time>? and create_time<?
            Integer newUserCount = getUserCount(beginTime, endTime);
            //统计截止到当天的所有用户 select count(*) from user where  create_time<?
            Integer totalUserCount = getUserCount(null, endTime);

            newUserConunts.add(newUserCount);
            totalUserConunts.add(totalUserCount);
        }

        String newUserStr = StringUtils.join(newUserConunts, ",");
        String totalUserStr = StringUtils.join(totalUserConunts, ",");

        return UserReportVO.builder()
                .dateList(dateStr)
                .newUserList(newUserStr)
                .totalUserList(totalUserStr)
                .build();
    }

    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        // 日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03
        List<LocalDate> dateList = getLocalDateList(begin, end);

        //每日订单数，以逗号分隔，例如：260,210,215
        //每日有效订单数，以逗号分隔，例如：20,21,10
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            // select * from orders where order_time >=? and order_time<=? and status = ?
            Integer orderCount = getOrderCount(beginTime, endTime, null);

            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }

        //订单总数  有效订单数 订单完成率
       /* int totalOrderCount = 0;
        for (Integer count : orderCountList) {
            totalOrderCount+=count;
        } */
        // [1,2,3]  1=a 2=b  3=a  3=b
        /*Integer totalOrderCount = orderCountList.stream().reduce((a, b) -> {
            return Integer.sum(a,b);
        }).get();*/

        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer totalValidOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = totalValidOrderCount.doubleValue() / totalOrderCount;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(totalValidOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> goodsSalesDTOList =  orderDetailMapper.getNameAndNumByOrderTime(beginTime,endTime);

        //商品名称列表，以逗号分隔，例如：鱼香肉丝,宫保鸡丁,水煮鱼
        //销量列表，以逗号分隔，例如：260,215,200
        // List<String> nameList = new ArrayList<>();
        // List<Integer> numberList = new ArrayList<>();
        /*for (GoodsSalesDTO goodsSalesDTO : goodsSalesDTOList) {
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber());
        }*/
        List<String> nameList =  goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList =  goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    @Override
    public void exportExcel(HttpServletResponse response) {
        LocalDate beginTime = LocalDate.now().minusDays(30);
        LocalDate endTime = LocalDate.now().minusDays(1);

        //1.查询金30天的运营数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(beginTime, LocalTime.MIN), LocalDateTime.of(endTime, LocalTime.MAX));
        log.info("最近30天运营数据：{}",businessData);
        //2。将查询到的数据添加到模板中
        InputStream is =null;
        XSSFWorkbook workbook=null;
        try {
            is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
            //读取模板生成excel对象
            workbook = new XSSFWorkbook(is);
            //获取sheet
            XSSFSheet sheet = workbook.getSheetAt(0);

            //获取第二行row对象
            XSSFRow row = sheet.getRow(1);
            //给第二行第二列填充数据
            row.getCell(1).setCellValue("时间:"+beginTime+"至"+endTime);

            //获取第四行row对象
            row = sheet.getRow(3);
            //给营业额，完成率，新增用户数赋值
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());

            //获取第五行，并赋值
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            //填充每一天的营业数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = beginTime.plusDays(i);
                BusinessDataVO businessRowData  = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                row = sheet.getRow(7+i);

                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessRowData.getTurnover());
                row.getCell(3).setCellValue(businessRowData.getValidOrderCount());
                row.getCell(4).setCellValue(businessRowData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessRowData.getUnitPrice());
                row.getCell(6).setCellValue(businessRowData.getNewUsers());
            }

            //通过输出流，输出excel文件给浏览器
            ServletOutputStream out = response.getOutputStream();
            workbook.write(out);

            // out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
           if(workbook!=null){
               try {
                   workbook.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
        }

    }

    private Integer getOrderCount(LocalDateTime beginTime, LocalDateTime endTime, Integer status) {
        Map map = new HashMap();
        map.put("begin", beginTime);
        map.put("end", endTime);
        map.put("status", status);

        return ordersMapper.getCountByOrderTimeAndStatus(map);
    }

    private Integer getUserCount(LocalDateTime beginTime, LocalDateTime endTime) {
        Map map = new HashMap();
        map.put("begin", beginTime);
        map.put("end", endTime);
        return userMapper.getCountByCreateTime(map);
    }
}
